<template>
  <div class="basePlateFail">
    <TopFilter
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="true"
      :onRowSelectChange="onRowSelectChange"
      :onColumnsChange="columns => this.columns = columns"
    >
    <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="approvalHandle(props,'1')">审批</el-button>
      </template>
    </FilterTable>
    <!-- 审批 -->
    <BaseDialog
      :visible.sync="approvalVisible"
      title=""
      width="30%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 80px)', overflow: 'auto', }"
    >
        <div style="text-align: center;margin: 3vw 0 0 0;">
          <el-button size="small" type="primary" @click="allowHandler">批准</el-button>
          <el-button size="small" type="primary" @click="rejectHandler">驳回</el-button>
          <el-button size="small" type="primary" @click="distributionHandler">分配</el-button>
        </div>
    </BaseDialog>
    <!-- 明细页面 -->
    <Drawer
      :visible.sync="visible"
      title="客户信息"
      :width="1000"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"

    >
      <div class="father" style="float: right;position: relative;z-index: 99;">
        <div class="son">
          <el-button size="small" type="primary" @click="closeHandler">返回</el-button>
          <el-button size="small" type="primary" :disabled="formData.reviewStatus ==70631002?true:false" @click="allowHandler('show')">批准</el-button>
          <el-button size="small" type="primary" :disabled="formData.reviewStatus ==70631002?true:false" @click="rejectHandler('show')">驳回</el-button>
          <el-button size="small" type="primary" :disabled="formData.reviewStatus ==70631002?true:false" @click="distributionHandler('show')">再分配</el-button>
          <el-button size="small" :disabled="formData.isComplete == 10041001?true:false" type="primary" @click="followUp">跟进</el-button>
          <el-button size="small" type="primary" @click="continueBuy">续购</el-button>
        </div>
      </div>
      <custsDetail :type="handleType" :rowData="formData" @close="closeHandler" />
    </Drawer>

    <BaseDialog
      :visible.sync="followVisible"
      title="基盘跟进"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <followModal :type="handleType" :baseType="baseType" :rowData="formData" @close="closeHandler_follow" />
    </BaseDialog>

    <Drawer
      :visible.sync="customerVisible"
      title="新增潜客"
      :width="1000"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <cluesModel :type="handleType" :rowData="formData" @close="closeHandler_Customer" />
    </Drawer>
    <!-- 分配 -->
    <el-dialog
      :visible.sync="consultVisible"
      title="选择顾问"
      :type="consultHandleType"
      :rowData="consultFormData"
      width="80%">

        <el-radio-group v-model="radio">
          <el-radio v-for="(item, index) in consults" :key="index" style="width:100px" :label="item.userId">{{ item.userName }}</el-radio>
        </el-radio-group>
        <div
          :style="{
            marginTop:'10px',
            textAlign: 'right'
          }"
        >
          <el-button @click="consultcloseVisible">取 消</el-button>
          <el-button type="primary" @click="consultHandler">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { getReviewRelateAudit,setPlateApprove,setPlateTurnDown,setPlateDistribution,getUsersByPosition } from '@/api/potenCus/basePlate/basePlateFail/index';
import { dictionary } from '@/utils/dictMixin';
import { IDNumber, phone } from '@/utils/validate'
import custsDetail from '@/pages/potenCus/basePlate/cust1Manage/custsDetail';
import followModal from './../basePlateFollow/modal'
import cluesModel from './../../customer/potenCusManage/cluesModel';
import { formatDates, formatDat } from '@/utils/validate';
import {
  getDirSalesName
 } from '@/api/potenCus/customer/approval';
import {getUserInfoByRolePosition,getUserInfo} from '@/api/potenCus/customer/exhibition'
export default {
  name: 'basePlateFail',
  mixins: [dictionary],
  components: {
    custsDetail,
    followModal,
    cluesModel
  },
  data() {
    return {
      baseType:"fail",
      topFilterList: this.createTopFilters(),
      fetchParams: {"reviewStatus":[70631001]},
      visible: false,
      fetchApi: getReviewRelateAudit,
      columns: this.createTableColumns(),
      dataType:'',
      handleType: '',
      formData: {},
      approvalVisible:false,
      rowDataList:[],
      followVisible: false,   //跟进
      customerVisible:false,
      formData_Customer: {},
      formData_follow: {},
      consultHandleType: '',
      consultFormData: {},
      radio: '',
      consults:[],
      consultVisible:false,
      distriType:"",
      reviewStatus:"",
    };
  },
  methods: {
    createTopFilters() {
        return [
            {
            type: 'INPUT',
            label: '潜客名称',
            fieldName: 'potentialcustomerName',
            placeholder: '请输入...',
            initialValue: '',
            style: { width: '240px' },
            },
            {
            type: 'INPUT',
            label: '客户名称',
            fieldName: 'customerName',
            placeholder: '请输入...',
            initialValue: '',
            style: { width: '240px' },
            },
            {
            type: 'INPUT',
            label: '联系人',
            fieldName: 'contactName',
            placeholder: '请输入...',
            initialValue: '',
            style: { width: '240px' },
            },
            {
              type: 'INPUT',
              label: '联系电话',
              fieldName: 'contactPhone',
              placeholder: '',
              style: { width: '240px' },
              // rules: [{ required: true, message: '请输入手机号码', trigger: 'blur' },
              // { trigger: 'blur', validator: phone }]
            },
            {
              type: 'RANGE_DATE',
              label: '申请日期',
              fieldName: 'beginTime|endTime',
              placeholder: '请输入...',
              initialValue: '',
              style: { width: '240px' },
            },
            {
              type:'INPUT',
              label: 'VIN',
              fieldName: 'vin',
              placeholder: '请输入...',
              initialValue: '',
              style: { width: '240px' },
            },
            {
              type: 'SELECT',
              label: '审核状态',
              fieldName: 'reviewStatus',
              placeholder: '请输入...',
              initialValue:70631001,
              style: { width: '240px' },
              itemList: [{ text: '未审核', value: 70631001 }, { text: '已审核', value: 70631002 }],
            },
            {
              type: 'SELECT',
              label: '客户等级',
              fieldName: 'level',
              placeholder: '请输入...',
              style: { width: '240px' },
              itemList: this.createDictList('7049'),
            },
            {
              type: 'SELECT',
              label: '申请人',
              fieldName: 'consultant',
              placeholder: '请输入...',
              style: { width: '240px' },
              itemList: [],
            }
        ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 120,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" disabled={props.row.reviewStatus ==70631002?true:false} type="text" onClick={() => this.editHandle(props.row,2)}>
                  审核
                </el-button>
                <el-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '客户编号',
          dataIndex: 'potentialCustomerNo',
          sorter: true,
          width:200,
          //filter: true,
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          sorter: true,
          //filter: true,
          width:200,
          filterType: 'checkbox',
          filterItems: this.createDictList('1523'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '1523')}</span>;
          }
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '客户电话',
          dataIndex: 'mobilePhone',
          sorter: true,
          width:200,
          //filter: true,
          filterType: 'input'
        },
        {
          title: '联系人',
          dataIndex: 'contactName',
          sorter: true,
          //filter: true,
          width:200,
          filterType: 'input'
        },
        {
          title: '联系人电话',
          dataIndex: 'contactPhone',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '客户等级',
          dataIndex: 'level',
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('7049'),
          render: props => {
            return <span>{this.createDictText(props.row.level, '7049')}</span>;
          }
        },
        {
          title: '销售单号',
          dataIndex: 'viNo',
          sorter: true,
          //filter: true,
          width:200,
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          sorter: true,
          width:200,
          //filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          //filter: true,
          width:200,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '配置',
          dataIndex: 'packageName',
          sorter: true,
          width:200,
          //filter: true,
          filterType: 'input'
        },
        {
          title: '成交日期',
          dataIndex: 'transactionTime',
          sorter: true,
          //filter: true,
          width:200,
          filterType: 'input',
          render: props =>{
            return <span>{ formatDat(props.row.transactionTime) }</span>
          }
        },
        {
          title: '申请人',
          dataIndex: 'consultantName',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '申请时间',
          dataIndex: 'factActionDate',
          sorter: true,
          width:200,
          //filter: true,
          filterType: 'input',
          render: props =>{
            return <span>{ formatDates(props.row.factActionDate) } </span>
          }
        },
        {
          title: '经过情形',
          dataIndex: 'scene',
          sorter: true,
          //filter: true,
          width:200,
          filterType: 'input'
        },
        {
          title: '流失原因',
          dataIndex: 'resultReason',
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('7055'),
          render: props => {
            return <span>{this.createDictText(props.row.resultReason, '7055')}</span>;
          }
        },
        {
          title: '审核状态',
          dataIndex: 'reviewStatus',
          sorter: true,
          //filter: true,
          width:200,
          filterType: 'checkbox',
          filterItems: this.createDictList('7063'),
          render: props => {
            return <span>{this.createDictText(props.row.reviewStatus, '7063')}</span>;
          }
        },
        {
          title: '审核结果',
          dataIndex: 'auditResult',
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('7064'),
          render: props => {
            return <span>{this.createDictText(props.row.auditResult, '7064')}</span>;
          }
        }
      ];
    },
    async init(){
        // 查询所属顾问
         let params = {
            positionCodes: [10061015],
            menuId: 204010
          }
          getUsersByPosition(params).then((result) => {
          if (result.resultCode === 200) {
            let orginList = result.data;
            this.consultantList = orginList.filter((item,index,array) => {
              return array.findIndex(el=>el.userId==item.userId)===index
            })
            this.topFilterList.find(item => item.fieldName === 'consultant').itemList = this.consultantList.map(x => ({ value: x.userId, text: x.userName ,userCode:x.userCode}));
            this.consults = this.consultantList;
         }
            // console.log(result,"result")
            // this.topFilterList.find(item=>item.fieldName == "consultant").itemList= result.data.map(x => ({ value: x.userId, text: x.userName ,userCode:x.userCode}));
          })
      await getUserInfo().then(res => {
          if(res.resultCode == 200){
            this.userId=res.data.userInfo.userId
            let param = {
              companyId:res.data.userInfo.companyId,
              positionCode:10061015
            };
            getUserInfoByRolePosition(param).then(res => {
              if(res.resultCode == 200){
                this.RolePosition=res.data.map(x => ({ value: x.userId, text: x.employeeName ,orgId:x.orgId}))
                // this.RolePosition=_.uniqBy(this.RolePosition,'value')
                console.log(this.RolePosition,"this.RolePosition")
                // this.topFilterList.find(item=>item.fieldName == "consultant").itemList = this.RolePosition
              }else{
                this.$message.error('获取人员列表失败!');
              }
            })
          }else{
            this.$message.error('获取当前登录用户信息失败!');
          }
        });
    },
    getCookie(){
        let allCookie=document.cookie.split(';')
        allCookie.forEach(x=>{
            if(x.indexOf('dataType') > -1 ){
              this.dataType=x.split('=')[1]
            }
        })
        //判断是否为厂端
        // if(this.dataType != 10461001){
        // }else{
        // }
    },
    //行选择
    onRowSelectChange(row){
      // console.log(row,"row")
      this.rowDataList.push(row)
      /* let arr= ""
      row.forEach(x=>{
        if(x.reviewStatus ==70631002){
          arr=x.reviewStatus
        }else{
          this.rowDataList.push(row)
        }
      })
      if(arr == 70631002){
        this.$message.info('已审核的不允许再次审核!');
      } */
      // console.log(this.rowDataList,"this.rowDataList",arr)
    },
    //审批
    approvalHandle(){
      // console.log("审批",type,this.rowDataList)
      if(this.rowDataList && this.rowDataList[this.rowDataList.length-1].length > 0){
          let arr= ""
          this.rowDataList[this.rowDataList.length-1].forEach(x=>{
            if(x.reviewStatus ==70631002){
              arr=x.reviewStatus
            }else{
              this.approvalVisible=true
            }
          })
          if(arr == 70631002){
            this.$message.info('已审核的不允许再次审核!');
          }
      }
    },
    //审核
    editHandle(row,type) {
      this.approvalVisible=true
      this.rowDataList.push(row)
      console.log(this.rowDataList,"审核",type)
    },
    //查看
    showHandle(row){
      console.log(row,"查看")
      this.formData = row;
      this.visible=true
    },

    //批准
    allowHandler(type){
      console.log(this.rowDataList,"批准",this.rowDataList[this.rowDataList.length-1])
      if(type == "show"){
        let paramsData = {}
        paramsData.plateDistrDTOS = [this.formData]
        setPlateApprove(paramsData).then(res=>{
          if(res.resultCode == 200){
            this.$message.success('批准成功!');
            this.approvalVisible=false
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          }
        })
      }else{
        console.log(this.rowDataList[this.rowDataList.length-1],".length")
        if(this.rowDataList[this.rowDataList.length-1].length>1){
            let paramsData = {}
            paramsData.plateDistrDTOS = this.rowDataList[this.rowDataList.length-1]
            setPlateApprove(paramsData).then(res=>{
            if(res.resultCode == 200){
              this.$message.success('批准成功!');
              this.approvalVisible=false
              // 重新加载
              this.fetchParams = { ...this.fetchParams };
            }
        })
        }else{
          let paramsData = {}
          paramsData.plateDistrDTOS = [this.rowDataList[this.rowDataList.length-1]]
          setPlateApprove(paramsData).then(res=>{
            if(res.resultCode == 200){
              this.$message.success('批准成功!');
              this.approvalVisible=false
              // 重新加载
              this.fetchParams = { ...this.fetchParams };
            }
        })
        }

      }
    },
    rejectHandler(type){
      console.log("驳回",this.rowDataList[this.rowDataList.length-1])
      if(type == "show"){
        let paramsData = {}
        paramsData.plateDistrDTOS = [this.formData]
        setPlateTurnDown(paramsData).then(res=>{
          if(res.resultCode == 200){
            this.$message.success('驳回成功!');
            this.approvalVisible=false
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          }
        })
      }else{
        if(this.rowDataList[this.rowDataList.length-1].length > 1){
            let paramsData = {}
            paramsData.plateDistrDTOS = this.rowDataList[this.rowDataList.length-1]
            setPlateTurnDown(paramsData).then(res=>{
              if(res.resultCode == 200){
                this.$message.success('驳回成功!');
                this.approvalVisible=false
                // 重新加载
                this.fetchParams = { ...this.fetchParams };
              }
            })
        }else{
            let paramsData = {}
            paramsData.plateDistrDTOS = [this.rowDataList[this.rowDataList.length-1]]
          setPlateTurnDown(paramsData).then(res=>{
          if(res.resultCode == 200){
            this.$message.success('驳回成功!');
            this.approvalVisible=false
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          }
        })
        }

      }
    },
    distributionHandler(type){
      console.log("分配",this.rowDataList[this.rowDataList.length-1])
      this.consultVisible=true
      // let roleType = this.dataType === 'clue' ? '10061012':'10061012,10061015';
      // getUsersByPosition(1,roleType)

      this.distriType = type
    },
    // 跟进
    followUp(){
      this.handleType = 'add';
      this.followVisible = true;
    },
    // 续购
    continueBuy(){
      this.handleType = 'addForbase';
      this.customerVisible = true;
    },

    //搜索
    changeHandle(val) {
        console.log(val,"val")
      this.fetchParams = Object.assign({ sort: 'wayId', order: 'desc'}, val);
    },
    //重置
    collapseHandle() {
      console.log(123)
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(type) {
      this.visible = false;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_follow(val, type) {
      this.followVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_Customer(val, type) {
      this.customerVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    consultHandler(){
      if (this.consult === 0) {
        this.activateChange()
      } else if (this.radio) {
        if (this.row) {
          this.approvalChange('2', this.row)
        } else {
          this.approvalChange('2')
        }
      } else {
        this.$message.info('请先选择顾问');
      }
      // this.consultcloseVisible()
    },
    approvalChange(num,data){
      console.log(num,data,"驳回",this.radio)
         if(this.distriType == "show"){
           console.log("show")
          this.formData.distributionConsultant=this.radio
          let paramsData = {}
          paramsData.plateDistrDTOS = [this.formData]
          setPlateDistribution(paramsData).then(res=>{
            if(res.resultCode == 200){
              this.$message.success('分配成功!');
              this.approvalVisible=false
              this.consultcloseVisible()
              // 重新加载
              this.fetchParams = { ...this.fetchParams };
            }
          })
        }else{
          console.log(this.rowDataList[this.rowDataList.length-1])
          if(this.rowDataList[this.rowDataList.length-1].length>1){
              this.rowDataList[this.rowDataList.length-1].map(x=>{
                x.distributionConsultant=this.radio
              })

              let paramsData = {}
              paramsData.plateDistrDTOS = this.rowDataList[this.rowDataList.length-1]
              setPlateDistribution(paramsData).then(res=>{
              if(res.resultCode == 200){
                this.$message.success('分配成功!');
                this.consultcloseVisible()
                this.approvalVisible=false
                // 重新加载
                this.fetchParams = { ...this.fetchParams };
              }
            })
          }else{
            console.log("show3",this.rowDataList[this.rowDataList.length-1])
            if(typeof(this.rowDataList[this.rowDataList.length-1]) == 'object'){
              this.rowDataList[this.rowDataList.length-1].distributionConsultant=this.radio

              let paramsData = {}
              paramsData.plateDistrDTOS = [this.rowDataList[this.rowDataList.length-1]]
              setPlateDistribution(paramsData).then(res=>{
              if(res.resultCode == 200){
                this.$message.success('分配成功!');
                this.consultcloseVisible()
                this.approvalVisible=false
                // 重新加载
                this.fetchParams = { ...this.fetchParams };
              }
            })
            }else{
              this.rowDataList[this.rowDataList.length-1].forEach(x=>{
                x.distributionConsultant=this.radio
              })
              let paramsData = {}
              paramsData.plateDistrDTOS = this.rowDataList[this.rowDataList.length-1]
              setPlateDistribution(paramsData).then(res=>{
              if(res.resultCode == 200){
                this.$message.success('分配成功!');
                this.consultcloseVisible()
                this.approvalVisible=false
                // 重新加载
                this.fetchParams = { ...this.fetchParams };
              }
            })
            }

          }

        }
    },
    consultcloseVisible(){
      this.radio = ''
      this.consultVisible = false;
      this.approvalVisible=false
    },
    // 顾问列表
    async getDirSalesName() {
      const res = await getDirSalesName({menuId: 202050,positionCode: '10061015,10061012'});
      // console.log('车型信息', res)
      if (res.resultCode === 200) {
        this.consults = res.data;
      }
    },
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getCookie()
    this.init()

  },
  created() {
  }
};
</script>

<style lang="less" >

</style>
